package tech.cyhk.cloud.demo.predicate;

import com.alibaba.nacos.common.utils.StringUtils;
import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.cloud.gateway.handler.predicate.QueryRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.RoutePredicateFactory;
import org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.function.Predicate;

/**
 * 参考{@link QueryRoutePredicateFactory}实现
 * {@link RouteDefinitionRouteLocator} 会用{@link NameUtils#normalizeRoutePredicateName}将{@link RoutePredicateFactory}部分截断，完成前缀映射
 *
 * @author swd
 * @date 2025/1/23
 */
@Component
public class VipRoutePredicateFactory extends AbstractRoutePredicateFactory<VipRoutePredicateFactory.Config> {


    public VipRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("key", "value");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return (GatewayPredicate) serverWebExchange -> {
            String first = serverWebExchange.getRequest().getQueryParams().getFirst(config.getKey());
            return StringUtils.equals(first, config.getValue());
        };
    }

    @Validated
    @Data
    static class Config {
        private String key;
        private String value;
    }
}
